<template>
  <div v-drag class="box">
    <div class="header"></div>
    <div>内容</div>
  </div>
</template>

<script setup lang="ts">
import type { Directive, DirectiveBinding } from "vue";

const vDrag: Directive<any, void> = (
  el: HTMLElement,
  _binding: DirectiveBinding
) => {
  let dragElement: HTMLDivElement = el.firstElementChild as HTMLDivElement; // 获取需要拖动的元素头部

  const mouseDown = (e: MouseEvent) => {
    // 获取鼠标相对元素的位置
    let X = e.clientX - el.offsetLeft;
    let Y = e.clientY - el.offsetTop;

    const move = (e: MouseEvent) => {
      // 元素移动的位置
      el.style.left = e.clientX - X + "px";
      el.style.top = e.clientY - Y + "px";
    };

    document.addEventListener("mousemove", move);
    document.addEventListener("mouseup", () => {
      document.removeEventListener("mousemove", move);
    });
  };

  dragElement.addEventListener("mousedown", mouseDown);
};
</script>

<style scoped>
.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  height: 400px;
  border: 2px solid #000;

  .header {
    width: 100%;
    height: 50px;
    background: #999;
    cursor: move;
  }
}
</style>
